package com.atwu.wl2022.service.impl;

import com.atwu.wl2022.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author wulejay
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

	/**
	 * 使用@Value注入application.properties中指定的用户名
	 */
	@Value("${spring.mail.username}")
	private String from;

	/**
	 * 用于发送文件
	 */
	@Autowired
	 JavaMailSender mailSender;

	@Override
	public void sendHtmlMail(String to, String subject, String content) {
		log.info("发送邮件开始：{},{},{}", to, subject, content);
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			helper = new MimeMessageHelper(message);
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content, true);
			mailSender.send(message);
			log.info("发送邮件成功");
		} catch (MessagingException e) {
			log.error("发送邮件失败", e);
		}
	}


}